from rest_framework.serializers import ModelSerializer, ReadOnlyField
from rest_framework import serializers
from alarm.models import Alarm, AlarmLocation
from utils.driver_vehicle_aralm_map import Driver_Vehicle_Map


class AlarmLocationSerializer(ModelSerializer):
    class Meta:
        model = AlarmLocation
        fields = '__all__'


class AlarmSerializer(ModelSerializer):
    vehicle_id = serializers.IntegerField(write_only=True)
    location = AlarmLocationSerializer(write_only=True)
    license_number = serializers.ReadOnlyField(source='vehicle.license_number')

    class Meta:
        model = Alarm
        fields = (
            'id', 'vehicle_id', 'category', 'location',
            'start_time', 'end_time', 'license_number',
            'media_uri_category', 'media_uri',
        )

    def create(self, validated_data):
        related_data = validated_data.pop('location')
        location = AlarmLocation.objects.create(**related_data)
        alarm = Alarm.objects.create(location=location, **validated_data)
        return alarm

    def to_representation(self, instance):
        alarm_type = '其他报警'
        if instance.category in Driver_Vehicle_Map:
            alarm_type = Driver_Vehicle_Map[instance.category]
        res = {
            "id": instance.id,
            "license_number": instance.vehicle.license_number,
            "category": instance.get_category_display(),
            "start_time": instance.start_time.strftime("%Y-%m-%d %H:%M:%S"),
            "end_time": instance.end_time.strftime("%Y-%m-%d %H:%M:%S"),
            "media_uri_category": instance.get_media_uri_category_display(),
            "media_uri": instance.media_uri,
            "alarm_type": alarm_type
        }
        if instance.media_uri_category == 2:  # 视频
            # 获取视频封面图片
            img = Alarm.objects.filter(vehicle=instance.vehicle, start_time=instance.start_time,
                                       media_uri_category=1).first()
            if img:
                res['cover_image'] = img.media_uri
            else:
                res['cover_image'] = ''
        return res


class AlarmRetrieveSerializer(ModelSerializer):
    class Meta:
        model = Alarm
        fields = ('media_uri',)


class AlarmCategorySerializer(ModelSerializer):
    class Meta:
        model = Alarm
        fields = ['category']
